'use strict';

const base = require('../base/controllerBase');

class HomeController extends base {
    async createTenant() {
        const {ctx, service} = this;
        try {
            const {body} = ctx.request;
            const model = {
                // tenantCode: {type: 'string'},
                tenantName: {type: 'string'},
                tenantType: {type: 'string'},
                createUser: {type: 'string'},
                menu: {type: 'array'}
            };
            console.log(body);
            body.tenantCode='TEN'+new Date().valueOf();
            ctx.validate(model, body);
            const result = await service.tenantService.createTenant(body);

            ctx.body = result;
            ctx.status = 200;
        } catch (e) {
            const _message = e && e.message ? e.message : this.ERROR_MSG;
            console.log(e);
            ctx.body = {status: 'error', message: _message, result: e};
            ctx.status = 200;
        }
    }

    async findTenant() {
        const {ctx} = this;
        try {
            const {body} = ctx.request;
            const model = {
                tenantCode: {type: 'string'}
            };

            ctx.validate(model, body);
            delete body['isSuRegister'];
            // const result = await ctx.model.Tenant.findOne(body);
            const result = await ctx.app.dbs.findOne('Tenant', body);
            ctx.body = {status: 'ok', result};
            ctx.status = 200;
        } catch (e) {
            const _message = e && e.message ? e.message : this.ERROR_MSG;
            ctx.body = {status: 'error', message: _message, result: e};
            ctx.status = 200;
        }
    }

    async findTenants() {
        const {ctx, service} = this;
        const result = await service.tenantService.findTenants();

        ctx.body = result;
        ctx.status = 200;
    }

    async deleteTenant() {
        const {ctx, service} = this;
        try {
            const {body} = ctx.request;
            const model = {
                tenantCode: {type: 'string'}
            };
            ctx.validate(model, body);

            const result = await service.tenantService.deleteTenant(body);

            ctx.body = result;
            ctx.status = 200;
        } catch (e) {
            const _message = e && e.message ? e.message : this.ERROR_MSG;
            ctx.body = {status: 'error', message: _message, result: e};
            ctx.status = 200;
        }
    }
}

module.exports = HomeController;
